Java For Humans: Learn to Code Life by Lincoln Daniel

Java For Humans: Learn to Code Life by Lincoln Daniel

Author:Lincoln Daniel
Language: eng
Format: azw3, epub, pdf
Publisher: ModernNerd
Published: 2016-12-26T08:00:00+00:00


Learning to Manipulate Data

56

Possible Output

I'm going out!

That’s it. We now know how to generate random values with or without bounds as well as random booleans. Further, we have learned how to use random values to make decisions in our code with if statements. You can now employ your new knowledge to add randomness to your programs and make them that much more interesting.

Control Flow Statements: Loops

We’ve come a long way from the last time we learned about control flow statements in the Decisions chapter. Great work on making it this far. This chapter will cover loops, which allow you to execute blocks of code more than once.

In the Decisions chapter, we learned that Java executes our program line by line from top to bottom. To change that, we could use if statements to only execute a block of code when a condition is true and another block of code otherwise. That is the basis of control flow in Java. With decision-making statements, we can choose to skip some lines of code during execution, but what if we want to repeat a line of code multiple times while a condition is true? That’s where loops come into play.

Why Loops are Important & Useful

Loops in Java allow us to repeat some of our code a fixed number of times or so long as a condition remains true. There are three basic forms of loops in Java, but we will only be focusing on two of them here because they are the most important and useful ones for beginners. We will learn about the for statement and the whilestatement. Both statements allow us to loop over blocks of code so long as a condition is true, but they do so a little differently from one another.

For Loop

The for statement allows us to loop over a block of code until a certain condition is satisfied. Because it loops, programmers often refer to it as the for loop. The for loop is best when you want to do something for a fixed number of times.

Say we want to loop over a range of numbers and print out each one along the way. We can do this best with a for loop. We will start from the first number, print it out, move to the next number to do the same thing, and continue until we’ve printed each number. Let’s print the numbers zero through nine:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.